﻿using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Text;
using System.Threading.Tasks;
using ZhiJiao.Dal;
using ZhiJiao.Models.Entities;
using ZhiJiao.Models.Entities.Enums;
using ZhiJiao.Service.Abstracts;
using ZhiJiao.Service.Dto;
using Module = ZhiJiao.Models.Entities.Module;

namespace ZhiJiao.Service.Services
{
    public class ModuleService:IModuleService
    {
        private readonly BackJson _res;
        private readonly ZJDbContext _db;
        public ModuleService(BackJson backJson,ZJDbContext zJDbContext)
        { 
            _res = backJson;
            _db = zJDbContext;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="id">当前表单模块ID（新增时为空）</param>
        /// <returns></returns>
       
        public BackJson GetParentModules(long? id,ModuleType type)
        {
            var query = _db.Modules.AsEnumerable();
            query = query.Where(m => m.IsDirectory && m.ParentModule == null && m.Type==type);
            if (id != null)
            {
                query = query.Where(m => m.Id != id);
            }
            var list = query.ToList().Select(m => new
            {
                label = m.Name,
                value = m.Id
            });
            _res.code = 0;
            _res.data = list;
            return _res;
        }

        /// <summary>
        /// 添加模块
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public BackJson AddModule(ModuleDto model)
        {
            try
            {
                ZhiJiao.Models.Entities.Module? parent = null;
                if (model.ParentModuleId != null)
                {
                    parent = _db.Modules.FirstOrDefault(m => m.Id == model.ParentModuleId);
                }
                var module = new ZhiJiao.Models.Entities.Module
                {
                    Name = model.Name!,
                    Sn = model.Sn!,
                    ParentModule = parent,
                    Icon = model.Icon!,
                    Url = model.Url!,
                    SortNum = model.SortNumber,
                    Flag = model.Flag,
                    CreatedTime=DateTime.Now,
                    UpdatedTime=DateTime.Now,
                    IsDirectory=parent==null?true:false,
                    Type=(ModuleType)model.Type
                };
                _db.Modules.Add(module);
                if (parent != null)
                {
                    parent.Children = new List<Module>();
                    parent.Children.Add(module);
                    _db.Modules.Update(parent);
                }
                _db.SaveChanges();
                _res.code = 0;
                _res.msg = "模块添加成功";
            }
            catch (Exception e)
            {
                _res.code = 1;
                _res.msg = e.Message;
            }
            return _res;
        }

        /// <summary>
        /// 修改模块
        /// </summary>
        /// <param name="module"></param>
        /// <returns></returns>
        public BackJson EditModuleSubmit(ModuleDto model)
        {
            var module = _db.Modules.FirstOrDefault(m => m.Id == model.Id);
            if (module != null)
            {
                try
                {
                    Models.Entities.Module? parent = null;
                    if (model.ParentModuleId != null)
                    {
                        parent = _db.Modules.FirstOrDefault(m => m.Id == model.ParentModuleId);
                    }
                    if (parent==null)
                    {
                        
                    }
                    module.SortNum = model.SortNumber;
                    module.Flag = model.Flag;
                    module.Icon = model.Icon!;
                    module.Url = model.Url!;
                    module.ParentModule = parent;
                    module.IsDirectory = model.IsDirectory;
                    module.UpdatedTime = DateTime.Now;
                    module.Name = model.Name!;
                    module.Sn = model.Sn!;
                    module.Type = (ModuleType)model.Type;
                    _db.Modules.Update(module);
                    _db.SaveChanges();
                    _res.code = 0;
                    _res.msg = "模块保存成功！";
                }
                catch (Exception e)
                {
                    _res.code = 1;
                    _res.msg = e.Message;
                }
            }
            else {
                _res.code = 1;
                _res.msg = "您所编辑的模块已被删除！";
            }
            return _res;
        }


        /// <summary>
        /// 获取列表
        /// </summary>
        /// <returns></returns>
        public BackJson GetModuleList()
        {
            try
            {
                var queryFirstLevel = _db.Modules.AsQueryable();
                queryFirstLevel = queryFirstLevel.Where(m => m.ParentModule == null).OrderBy(m =>m.SortNum);
                var firstList = queryFirstLevel.OrderBy(m=>m.SortNum). ToList();
                for (int i = 0; i < firstList.Count; i++)
                {
                    firstList[i].Children = _db.Modules.Where(m => m.ParentModule == firstList[i]).ToList();
                }
                var list = firstList.Select(p => new
                {
                    id = p.Id,
                    name = p.Name,
                    sn = p.Sn,
                    url = p.Url,
                    icon = p.Icon,
                    flag = p.Flag,
                    parentId= 9999,
                    type=p.Type,
                    isDirectory=p.IsDirectory,
                    children = p.Children?.OrderBy(c=>c.SortNum).Select(c => new
                    {
                        id = c.Id,
                        name = c.Name,
                        sn = c.Sn,
                        url = c.Url,
                        icon = c.Icon,
                        flag = c.Flag,
                        type=Convert.ToInt32(c.Type),
                        parentId=p.Id,
                        isDirectory=c.IsDirectory
                    })
                });
                _res.code = 0;
                _res.data = list;
            }
            catch (Exception e)
            {
                _res.code = 1;
                _res.msg = e.Message;
            }
            return _res;
        }

        /// <summary>
        /// 搜索模块
        /// </summary>
        public BackJson SearchModule(bool? flag,string? name, ModuleType? type)
        {
            try
            {
                var query = _db.Modules.AsQueryable();
                if (flag != null)
                {
                    query = query.Where(m => m.Flag == flag);
                }
                if (!string.IsNullOrEmpty(name))
                {
                    query = query.Where(m => m.Name.Contains(name));
                }
                if (type != null)
                {
                    query = query.Where(m => m.Type == type);
                }
                if (flag == null && name == null && type==null)
                {
                    return GetModuleList();
                }
                var list = query.ToList().Select(m => new {
                    id = m.Id,
                    name = m.Name,
                    sn = m.Sn,
                    url = m.Url,
                    icon = m.Icon,
                    flag = m.Flag,
                    isDirectory=m.IsDirectory,
                    type=Convert.ToInt32(m.Type),
                });

                _res.code = 0;
                _res.data = list;
            }
            catch (Exception e)
            {
                _res.code = 1;
                _res.msg = e.Message;
            }
            return _res;
        }

        /// <summary>
        /// 删除模块
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public BackJson DeleteModule(long id)
        {
            var module= _db.Modules.First(m => m.Id == id);
            var children= _db.Modules.Where(m => m.ParentModule == module).ToList();
            if (children.Count > 0)
            {
                _db.Modules.RemoveRange(children);
            }
            _db.Modules.Remove(module);
            _db.SaveChanges();
            _res.code = 0;
            _res.msg = "模块已被删除";
            return _res;
        }
    }
}
